<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export'" type="danger" size="small" @click="doExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="doAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" alt=""> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column
            label="工号"
            prop="workNumber"
          />
          <el-table-column
            label="聘用形式"
          >
            <template v-slot="scope">
              <span>{{ formateType(scope.row.formOfEmployment) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="doAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="doDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[3, 5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog :visible.sync="showDialog" title="新增员工">
      <EmpDialog @success="doSuccess" />
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog :visible.sync="showDialogRole" title="分配角色">
      <assignRole v-if="showDialogRole" :roleid="curId" @success="doSucs" @close="doClose" /></el-dialog>
  </div>
</template>
<script>
import { getEmployees, getDelEmployee } from '@/api/employee'
// 聘用形式的转换
import employeeENUM from '@/constant/employees'
const EMPLOYEE = employeeENUM.hireType.reduce((acc, cur) => { acc[cur.id] = cur.value; return acc }, {})
// console.log(EMPLOYEE)
// 导入子组件
import EmpDialog from '@/views/employees/empDialog.vue'
import ImageHolder from '@/views/employees/components/ImageHolder'
import assignRole from './assignRole.vue'
export default {
  components: { EmpDialog, ImageHolder, assignRole },
  data() {
    return {
      page: 1,
      size: 10,
      // 员工列表
      list: [],
      // 列表数量
      total: 0,
      // 是否显示弹窗
      showDialog: false,
      // 是否显示分配角色弹窗
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    // 在页面一打开时加载数据
    this.loadEmployees()
  },
  methods: {
    // 转换格式
    transfromType(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      /*
      rows ===>{'id':'01',mobile:'15698756988',...}
      */
      let header = Object.keys(rows[0])// ['id','mobile']
      const data = rows.map(item => {
        return header.map(key => {
          if (key === 'formOfEmployment') {
            return EMPLOYEE[item[key]]
          } else {
            return item[key]
          }
        })
      })// ['01','15698756988'...]
      // 中文表头
      header = header.map(key => {
        return map[key]
      })
      return { header, data }
    },
    // excel表导出
    doExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // excel表示导入的模块对象
        // console.log(excel)
        // 发ajax请求，获取数据
        const { data: res } = await getEmployees({ page: this.page, size: this.size })
        // console.log('员工信息', res)
        const { header, data } = this.transfromType(res.data.rows)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 按序号排序
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    async loadEmployees() {
      // 发送请求
      const { data: res } = await getEmployees({ page: this.page, size: this.size })
      console.log('员工信息', res)
      // 将数据绑定到data中
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 当前页面改变
    handleCurrentChange(curpage) {
      // console.log('当前您点击了第几页', curpage)
      // 更新页码
      this.page = curpage
      // 重发请求
      this.loadEmployees()
    },
    // handleSizeChange
    handleSizeChange(cursize) {
      // console.log('当前是每页几条', cursize)
      // 更新每页条数,统一跳转第一页
      this.size = cursize
      this.page = 1
      // 重发请求
      this.loadEmployees()
    },
    // 聘用状态格式化
    formateType(id) {
      return EMPLOYEE[id] || '未知'
    },
    // 删除员工信息
    doDel(id) {
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 发送请求
        const { data: res } = await getDelEmployee(id)
        // console.log('删除员工信息', res)
        // 如果当前页面只有一条数据,则让page--
        if (this.list.length === 1) {
          let page = this.page
          page--
          // 页码不能是0
          this.page = Math.max(1, page)
        }
        // 提示信息
        this.$message.success(res.message)
        // 刷新页面
        this.loadEmployees()
      }).catch(() => {
      })
    },
    // 增加员工
    doAdd() {
      // 显示弹窗
      this.showDialog = true
    },
    doSuccess() {
      // 添加成功
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.showDialog = false
      // 刷新列表
      this.loadEmployees()
    },
    // 分配角色
    doAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 子传父,关闭分配角色弹窗
    doSucs() {
      this.showDialogRole = false
    },
    // 关闭弹窗
    doClose() {
      this.showDialogRole = false
    }

  }
}
</script>
